import React from 'react';
import {
  Badge, Button, Col, Drawer, Empty, Input,
  Layout, Modal, Popconfirm, Row, Tooltip, Tree,
} from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import { PageHeaderLayout, StandardTable, SearchForm, PageCard, IconButton } from '../../components';
import { modalWidth, pageSize } from '../../../config';
import styles from './verify.css';
import Authorized from '../../utils/Authorized';
import tools from '../../utils';

const reqApi = 'count';
const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const statusData = [
  ['2', '待核实交费'],
  ['5', '已核实交费'],
];
const statusMapping = {};
const formItemLayout2 = {
  labelCol: { md: 6, xs: 7 },
  wrapperCol: { md: 18, xs: 17 },
};

class page extends React.Component {
  state = {
    currentNavi: '',
    loadingNavi: false,
    loadingContent: false,
    visibleTree: false, // "系部和专业"树显隐

    selectedRows: [],
    searchs: [],
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },

    record: {},
    visible: false,
    dialogLoading: false,
  };

  constructor(props) {
    super(props);
    statusData.map((item) => {
      const [key, value] = item;
      statusMapping[key] = value;
    });
  }

  componentDidMount() {
    this.funcGetNaviData();
  }

  // 获取菜单数据
  funcGetNaviData = () => {
    this.setState({ loadingNavi: true });

    const { props } = this;
    props.dispatch({
      type: reqApi + '/listSpecial',
      payload: {
        currentPage: 1,
        pageSize: 1000,
      },
    }).then(() => {
      this.setState({ loadingNavi: false });
      this.funcGetListData();
    });
  };

  // 获取列表数据
  funcGetListData = () => {
    this.setState({
      loadingContent: true,
      selectedRows: [],
    });

    const { state } = this;
    const { searchs, pagination } = state;
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    const newSearchs = [...searchs];

    if (state.currentNavi) {
      newSearchs.push({
        name: "specialId",
        value: state.currentNavi,
        searchType: "EQ",
        dataType: "STR",
      });
    }

    dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: current,
        pageSize,
        searchs: newSearchs,
      },
    }).then(() => this.setState({ loadingContent: false }));
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      record,
      visible: true,
    });
  };

  // 交费核实通过
  funcSave = () => {
    const { record } = this.state;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/allow',
        payload: {
          studentId: record.id,
          fee: values.fee - 0,
        },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];

        if (success) {
          this.setState({ visible: false });
          this.funcGetListData();
        }
      });
    });
  };

  // 交费核实撤销
  funcUndo = ({ id, name }) => {
    Modal.confirm({
      title: '撤销?',
      content: (
        <div>
          <div>你即将撤销以下记录：</div>
          <div>{name}</div>
          <div>请确认是否撤销？</div>
        </div>
      ),
      okText: "是",
      okType: "danger",
      cancelText: "否",
      onOk: () => {
        const { dispatch } = this.props;

        dispatch({
          type: reqApi + '/undo',
          payload: { studentId: id },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
        });
      },
    });
  };

  // 树实体
  treeBody = (data) => {
    const nodes = [];

    for (let i = 0; i < data.length; i += 1) {
      const item = data[i];
      const { key, title, children, selectable, pid } = item;
      const isSpec = pid > 0;

      nodes.push(
        <TreeNode
          key={key}
          selectable={selectable}
          title={isSpec ?
            (
              <div>
                <span>{title}</span>
                <Badge count={0} size='small' style={{ marginLeft: 4 }} />
              </div>
            ) :
            <div className={styles.treeNode}>{title}</div>
          }
        >
          {this.treeBody(children || [])}
        </TreeNode>,
      );
    }
    return nodes;
  };

  // 导航菜单
  naviMenu = () => {
    const { props } = this;
    const data = props[reqApi].dataSpecial;

    if (data.length) {
      return (
        <div
          style={{
            maxHeight: 'calc(100vh - ' + (window.isMobile ? 56 : 120) + 'px)',
            overflow: 'auto',
          }}
        >
          <Tree
            blockNode
            defaultExpandAll
            onSelect={(selectedKeys) => {
              this.setState({
                currentNavi: selectedKeys.length ? selectedKeys[0] : '',
                visibleTree: false,
              }, this.funcGetListData);
            }}
          >
            {this.treeBody(data)}
          </Tree>
        </div>
      );
    } else return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  };

  // 表格列
  columns = [
    {
      title: '学生姓名',
      dataIndex: 'name',
      width: 120,
      render: (text, record) => (
        <div>
          {record.status === '5' ? (
            <Authorized authority={() => tools.funcCheckValid(this.props, 'undo')}>
              <Popconfirm
                title={'确定要撤销“' + text + '”的交费状态？'}
                placement='bottom'
                onConfirm={() => this.funcUndo(record)}
              >
                <Tooltip title='撤销'>
                  <a>
                    <Icon type='undo' className={styles.adjustIcon} />
                  </a>
                </Tooltip>
              </Popconfirm>
            </Authorized>
          ) : null}
          <span className={styles.printBox}>
            <span>{text} </span>
            <a onClick={() => this.funcPrint(record.id)}>
              <Icon
                type='printer'
                theme='twoTone'
                title='打印'
                className={styles.printIcon}
              />
            </a>
          </span>
        </div>
      ),
    },
    {
      title: '身份证号',
      dataIndex: 'idCardNum',
      width: 180,
    },
    {
      title: '交费状态',
      dataIndex: 'status',
      width: 120,
      render: (text, record) => record.status === '2' ? (
        <Badge dot>
          <a onClick={() => this.funcOpenForm(record)}>
            {statusMapping[text]}
          </a>
        </Badge>
      ) : (
        <div>
          <Icon
            type='check-circle'
            theme='twoTone'
            twoToneColor='limegreen'
            style={{ fontSize: 16 }}
          />
          <span style={{ color: 'limegreen' }}>
            {' ' + statusMapping[text]}
          </span>
        </div>
      ),
    },
    {
      title: '交费金额',
      dataIndex: 'fee',
      width: 120,
      render: text => {
        if (text === '0') return '';
        let num = text - 0;
        num = num.toFixed(2);
        return '￥' + num + ' 元';
      },
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '是否住校',
      dataIndex: 'lodging',
      width: 80,
      render: text => text === '1' ? '住校' : '不住校',
    },
    {
      title: '报考专业',
      dataIndex: 'specialName',
    },
  ];

  // 查询列
  columnsSearch = [
    {
      title: '交费状态',
      dataIndex: 'status',
      type: 'select',
      sub: statusData,
    },
    {
      title: '学生姓名',
      dataIndex: 'name',
      type: 'text',
    },
  ];

  // 记录查询表单提交
  funcOnSubmitSearch = (searchs) => {
    const { state } = this;
    state.pagination.current = 1; // 进行查询操作则将页码归一
    this.setState({ searchs }, this.funcGetListData);
  };

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { data, total } = props[reqApi];

    return (
      <div>
        <SearchForm fields={this.columnsSearch} onSubmit={this.funcOnSubmitSearch} />

        <Button.Group>
          {window.isMobile ? (
            <Button
              type='primary'
              style={{ marginBottom: 16 }}
              onClick={() => this.setState({ visibleTree: true })}
            >选择专业</Button>
          ) : (
            <IconButton
              text='打印'
              icon='printer'
              disabled={!total}
              style={{ marginBottom: 16 }}
              onClick={() => this.funcPrint()}
            />
          )}
          <Authorized authority={() => tools.funcCheckValid(props, 'delete')}>
            <IconButton
              text='删除'
              type='danger'
              disabled={!state.selectedRows.length}
              style={{ marginBottom: 16 }}
              onClick={this.funcDelete}
            />
          </Authorized>
        </Button.Group>

        <StandardTable
          loading={state.loadingContent}
          columns={this.columns}
          data={{
            list: data,
            pagination: { ...state.pagination, total },
          }}
          selectedRows={state.selectedRows}
          onSelectRow={(selectedRows) => this.setState({ selectedRows })}
          onChange={(pageParams) => {
            const { pagination } = this.state;
            pagination.current = pageParams.current;
            this.funcGetListData();
          }}
          scrollX={1366}
        />
      </div>
    );
  };

  // 删除
  funcDelete = () => {
    const { state } = this;
    let names = [], ids = [];
    for (let i = 0; i < state.selectedRows.length; i += 1) {
      const item = state.selectedRows[i];
      const { id, name } = item;
      names.push(name);
      ids.push(id);
    }

    Modal.confirm({
      title: "删除?",
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{names + ''}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: "是",
      okType: "danger",
      cancelText: "否",
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + '/dele',
          payload: { ids: ids + '' },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
          else this.setState({ loading: false });
        });
      },
    });
  };

  // 检查交费金额是否大于零
  funcCheckValue = (_, value) => {
    if (!value) {
      return Promise.reject('请输入交费金额');
    }

    if (value <= 0) {
      return Promise.reject('交费金额必须大于零');
    }

    return Promise.resolve();
  };

  // 打印
  funcPrint = (idStr) => {
    const { selectedRows, searchs } = this.state;

    let ids = idStr;
    if (!ids) {
      const idsData = [];
      for (let i = 0; i < selectedRows.length; i += 1) {
        const item = selectedRows[i];
        const { id } = item;
        idsData.push(id);
      }
      ids = idsData + '';
    }

    localStorage.setItem('ids', ids);
    localStorage.setItem('searchs', JSON.stringify(searchs));
    localStorage.setItem('action', 'count');

    const w = window.innerWidth / 2, h = window.innerHeight;
    const win = window.open(
      'print.html?space=300',
      '_blank',
      'width=' + w + ',height=' + h + ',location=0,menubar=0,status=0,toolbar=0,scrollbars=1'
    );
    win.focus();
  };

  render() {
    const { props, state } = this;
    const { record } = state;
    const { form } = props;
    const { getFieldDecorator } = form;

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          bodyStyle={{
            padding: 0,
            overflow: 'hidden',
          }}
          children={(
            <Layout>
              {window.isMobile ? null : (
                <Sider
                  theme='light'
                  width={240}
                  style={{ borderRight: '1px solid gainsboro' }}
                >
                  {this.naviMenu()}
                </Sider>
              )}
              <Content
                style={{
                  padding: '16px 8px 0 8px',
                  backgroundColor: 'white',
                }}
              >
                {this.contentTable()}
              </Content>
            </Layout>
          )}
        />

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title='选择专业'
          visible={state.visibleTree}
          onClose={() => this.setState({ visibleTree: false })}
          bodyStyle={{ padding: 0 }}
        >
          {this.naviMenu()}
        </Drawer>

        <Modal
          width={modalWidth}
          title={(
            <div>
              <Icon type='fileSearch' style={{ fontSize: 18 }} />
              <span> {'核实“' + record.name + '”的交费信息'}</span>
            </div>
          )}
          visible={state.visible}
          bodyStyle={{ paddingBottom: 0 }}
          onOk={this.funcSave}
          onCancel={() => this.setState({ visible: false })}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ visible: false })}
            />,
            <IconButton
              key='save'
              text='确认收款'
              loading={state.dialogLoading}
              onClick={this.funcSave}
            />,
          ]}
        >
          <Form>
            <Row gutter={{ md: 24, sm: 8 }}>
              <Col md={12} sm={24}>
                <Form.Item label='学生姓名' {...formItemLayout2}>
                  <span>{record.name}</span>
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='性别' {...formItemLayout2}>
                  <span>{record.sex === '1' ? '男' : '女'}</span>
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='身份证号' {...formItemLayout2}>
                  <span>{record.idCardNum}</span>
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='手机号' {...formItemLayout2}>
                  <span>
                    {record.phone + (record.phoneBackup ? ', ' + record.phoneBackup : '')}
                  </span>
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='报名专业' {...formItemLayout2}>
                  <span>{record.specialName}</span>
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='是否住校' {...formItemLayout2}>
                  <span>{record.lodging === '1' ? '住校' : '不住校'}</span>
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='交费金额' {...formItemLayout2}>
                  {getFieldDecorator('fee', {
                    rules: [{ required: true, validator: this.funcCheckValue }],
                  })(
                    <Input autoFocus type='number' min={0} prefix='￥' suffix='元' />
                  )}
                </Form.Item>
              </Col>

            </Row>
          </Form>
        </Modal>

      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ count, menu }) => ({ count, menu }))(page2);
